<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>幻灯片轮播图效果</title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
			}
			.carousel {
				width: 640px;
				height: 400px;
				border: 1px solid black;
				position: relative;
				margin: 50px auto; 
				overflow: hidden;
			}
			ul {
				list-style: none;
				/* 写宽一点 避免浮动挤下去 */
				width: 5000px;
				position: relative;
				/* left: -640px; 就是下一张 */
				left: 0; 
				transition: .5s;
			}
			.carousel ul li {
				float: left;
			}
			.carousel .left {
				position: absolute;
				left: 20px;
				top: 0;
				bottom: 0;
				margin: auto;
				width: 50px;
				height: 50px;
				border-radius: 50%;
				background-color: gray;
			}
			.carousel .right {
				position: absolute;
				right: 20px;
				top: 0;
				bottom: 0;
				margin: auto;
				width: 50px;
				height: 50px;
				border-radius: 50%;
				background-color: gray
			}
		</style>
	</head>
	<body>
		<div class="carousel">
			<ul id="list">
				<li><img src="img/0.png" alt="化妆水"></li>
				<li><img src="img/1.jpg" alt="纸尿裤"></li> 
				<li><img src="img/2.jpg" alt="MUJI住宿"></li> 
				<li><img src="img/3.jpg" alt="MUJI周刊"></li> 
			</ul>
			<!-- # 号会刷新页面，所以用空语句 -->
			<a class="left" id="leftBtn" href="javascript:;"></a>
			<a class="right" id="rightBtn" href="javascript:;"></a>
		</div>
	</body>
	<script type="text/javascript">
		var left = document.getElementById("left");
		var right = document.getElementById("right")
		var list = document.getElementById("list")
		var cloneli =list.firstElementChild.cloneNode(true);
		list.appendChild(cloneli)
		// 当前ul的left值
		var index = 0;
		
		// 节流锁
		var lock = true;
		
		rightBtn.onclick = function() {
			// 判断锁的状态
			if(!lock) return;
			lock = false;
			// 最后一张图片会把过渡去掉，所以在开头加
			list.style.transition = '.5s'
			index++; 
			if(index > 3) {
				// 过渡结束后，将ul瞬间拉回0
				setTimeout(function(){
					// 取消过渡，要瞬间移动
					list.style.transition = 'none'
					list.style.left = 0;
					index = 0;
				},500) 
			} 
			list.style.left = -index * 640 + 'px'; 
			console.log(index);
			// 函数节流
			setTimeout(function(){
				lock = true;
			},500)
		}
		leftBtn.onclick = function() {
			// 判断锁的状态
			if(!lock) return;
			lock = false;
			// 判断是不是第0张，是，就要瞬间用假的替换真的
			if(index == 0) { 
				// 取消过渡，瞬间移动
				list.style.transition = 'none';
				// 直接瞬间移动到假图片
				list.style.left = -4 * 640 + 'px';
				setTimeout(function(){
					list.style.transition = '.5s'
					index = 3;
					list.style.left = -index * 640 + 'px'; 
				},0)
			} else {
				index--;
				list.style.left = -index * 640 + 'px'; 
			} 
			// 函数节流
			setTimeout(function(){
				lock = true;
			},500)
		}
	</script>
</html>
